package com.hqd.ch03.v51.reader.xml;

import com.hqd.ch03.v51.beans.factory.config.BeanDefinition;
import com.hqd.ch03.v51.factory.ConfigurableBeanFactory;
import com.hqd.ch03.v51.factory.config.BeanDefinitionHolder;
import com.hqd.ch03.v51.registry.BeanDefinitionRegistry;
import com.hqd.ch03.v51.utils.BeanDefinitionReaderUtils;
import org.apache.commons.lang3.StringUtils;

public class ParserContext {
    private final BeanDefinitionRegistry registry;

    public ParserContext(BeanDefinitionRegistry registry) {
        this.registry = registry;
    }

    public String registerWithGeneratedName(BeanDefinition bd) {
        String beanName = BeanDefinitionReaderUtils.generateBeanName(bd.getBeanClassName(), this.registry);
        if (StringUtils.isBlank(bd.getScope())) {
            bd.setScope(ConfigurableBeanFactory.SCOPE_SINGLETON);
        }
        this.registry.registerBeanDefinition(beanName, bd);
        return beanName;
    }

    public String registerWithGeneratedName(BeanDefinitionHolder bd) {
        String beanName = BeanDefinitionReaderUtils.generateBeanName(bd.getBeanClassName(), this.registry);
        if (StringUtils.isBlank(bd.getScope())) {
            bd.setScope(ConfigurableBeanFactory.SCOPE_SINGLETON);
        }
        setId(bd);
        this.registry.registerBeanDefinition(beanName, bd.getBeanDefinition());
        if (StringUtils.isBlank(bd.getId())) {
            bd.setId(beanName);
        }
        return beanName;
    }

    public void registerBeanDefinition(String beanName, BeanDefinitionHolder bd) {
        if (StringUtils.isBlank(bd.getScope())) {
            bd.setScope(ConfigurableBeanFactory.SCOPE_SINGLETON);
        }
        setId(bd);
        registry.registerBeanDefinition(beanName, bd.getBeanDefinition());
    }

    private void setId(BeanDefinitionHolder bd) {
        BeanDefinition beanDefinition = bd.getBeanDefinition();
        beanDefinition.setId(bd.getId());
    }

    public void registerBeanDefinition(String beanName, BeanDefinition bd) {
        if (StringUtils.isBlank(bd.getScope())) {
            bd.setScope(ConfigurableBeanFactory.SCOPE_SINGLETON);
        }
        registry.registerBeanDefinition(beanName, bd);
    }

    public BeanDefinitionRegistry getRegistry() {
        return registry;
    }
}
